package progress.exa28_2.part1;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Bank {

    private final double[] accounts;
    private Lock bankLock;
    private Condition sufficientFunds;

    public Bank(int n,double initBalance){
        accounts = new double[n];
        Arrays.fill(accounts,initBalance);
        bankLock = new ReentrantLock();
        sufficientFunds = bankLock.newCondition();

    }

    /**
     * 转账操作
     * @param from
     * @param to
     * @param amount
     * @throws InterruptedException
     */
    public void transfer(int from,int to,double amount) throws InterruptedException {
        bankLock.lock();
        try{
            while (accounts[from] < amount) {
                sufficientFunds.await();
            }
            System.out.println(Thread.currentThread());
            accounts[from] -= amount;
            System.out.println(amount+"from" + from+" to "+ to);
            accounts[to] += amount;
            System.out.println("Total balance : "+getTotalBalance());
            sufficientFunds.signalAll();
        }finally {
            bankLock.unlock();
        }
    }

    /**
     * 向指定账户存入指定数额的钱
     * @param to
     * @param amount
     * @return
     */
    public boolean saveMoney(int to,double amount) {
        bankLock.lock();
        try{
            System.out.println(Thread.currentThread());
            accounts[to] += amount;
            System.out.println("Total balance : "+getTotalBalance());
            sufficientFunds.signalAll();
        } finally {
            bankLock.unlock();
        }
        return true;
    }

    public double getTotalBalance() {
        bankLock.lock();
        try{
            double sum = 0;
            for(double a : accounts)
                sum +=a;
            return sum;
        }finally {
            bankLock.unlock();
        }
    }

}
